﻿using System;
using System.Collections.Generic;
using System.Diagnostics;
using BrnMall.Core;
using BrnMall.Manager;
using BrnMall.Manager.Domain.Product;
using BrnMall.Services;
using QIDong.WeApp.Models;
using WeiTap.Restful;

namespace QIDong.WeApp.Controllers
{

    /// <summary>
    /// 用户中心
    /// </summary>
    public class UserController : WebApi
    {
        #region 用户信息
        /// <summary>
        /// 获取用户信息
        /// </summary>
        /// <param name="uid">用户编号</param>
        /// <returns></returns>
        public UserInfoModel GetUserInfo(int uid)
        {
            try
            {
                var model = new UserInfoModel {UserInfo = Users.GetUserById(uid)};
                model.UserRankInfo = UserRanks.GetUserRankById(model.UserInfo.UserRid);
                var regionInfo = Regions.GetRegionById(model.UserInfo.RegionId);
                if (regionInfo == null) return model;
                model.RegionInfo = regionInfo;
                return model;
            }
            catch (Exception e)
            {
                Trace.TraceError(e.Message);
                throw;
            }
        }

        /// <summary>
        /// 编辑用户信息
        /// </summary>
        /// <param name="dto"></param>
        /// <returns></returns>
        public bool EditUserInfo(EditUserDto dto)
        {
            try
            {
                if(dto==null||dto.Uid<1)
                    throw new Exception("UID参数错误");
                var partUser = Users.GetPartUserById(dto.Uid);
                //验证昵称
                if (dto.NickName.Length > 50)
                {
                    throw new Exception("昵称的长度不能大于50");
                }
                else if (FilterWords.IsContainWords(dto.NickName))
                {
                    throw new Exception("昵称中包含禁止单词");
                }
                //验证真实姓名
                if (dto.RealName.Length > 50)
                {
                    throw new Exception("真实姓名的长度不能大于50");
                }
                //验证性别
                if (dto.Gender < 0 || dto.Gender > 2)
                    throw new Exception("请选择正确的性别");
                //验证身份证号
                if (dto.IdCard.Length > 0 && !ValidateHelper.IsIdCard(dto.IdCard))
                {
                    throw new Exception("请输入正确的身份证号");
                }
                if (dto.BDay.Length > 0 && !ValidateHelper.IsDate(dto.BDay))
                    throw new Exception("请选择正确的日期");
                //验证区域
                if (dto.RegionId > 0)
                {
                    var regionInfo = Regions.GetRegionById(dto.RegionId);
                    if (regionInfo == null || regionInfo.Layer != 3)
                        throw new Exception("请选择正确的地址");
                }
                //验证详细地址
                if (dto.Address.Length > 75)
                {
                    throw new Exception("详细地址的长度不能大于75");
                }
                //验证简介
                if (dto.Bio.Length > 150)
                {
                    throw new Exception("简介的长度不能大于150");
                }
                if(string.IsNullOrEmpty(dto.Bio))
                    dto.BDay = "1900-01-01";
                if(dto.Email.Length>0&&!ValidateHelper.IsEmail(dto.Email))
                throw new Exception("Email地址格式错误");
                if (dto.Mobile.Length > 0 && !ValidateHelper.IsMobile(dto.Mobile))
                    throw new Exception("手机号码格式错误");
                if (dto.Company.Length >50)
                {
                    throw new Exception("公司名字的长度不能大于50");
                }
                if (dto.JobTitle.Length > 50)
                {
                    throw new Exception("职位名字的长度不能大于50");
                }
                Users.UpdateUser(dto.Uid, partUser.UserName, WebHelper.HtmlEncode(dto.NickName), WebHelper.HtmlEncode(partUser.Avatar), dto.Gender, WebHelper.HtmlEncode(dto.RealName),
                    TypeHelper.StringToDateTime(dto.BDay), dto.IdCard, dto.RegionId,
                    WebHelper.HtmlEncode(dto.Address), WebHelper.HtmlEncode(dto.Bio),
                    dto.Company,dto.JobTitle);
                Users.UpdateUserEmailByUid(dto.Uid,dto.Email);
                Users.UpdateUserMobileByUid(dto.Uid, dto.Mobile);
                if (dto.NickName.Length > 0  && dto.RealName.Length > 0 && dto.BDay != "1900-01-01" &&dto.IdCard.Length > 0 &&dto.RegionId > 0 && dto.Address.Length > 0)
                {
                    Credits.SendCompleteUserInfoCredits(partUser.RegisterFromStoreId,ref partUser, DateTime.Now);
                }
                return true;
            }
            catch (Exception e)
            {
                Trace.TraceError(e.Message);
                throw;
            }
        }

        #endregion
        #region 收货地址

        /// <summary>
        /// 获取收货地址列表
        /// </summary>
        /// <param name="Uid">会员ID</param>
        /// <returns></returns>
        public List<FullShipAddressInfo> GetShipAddressList(int Uid)
        {
            if (Uid < 1)
                throw new Exception("会员ID必须大于0");

            return ShipAddresses.GetFullShipAddressList(Uid);
        }
        /// <summary>
        /// 获取默认收货地址列表
        /// </summary>
        /// <param name="uid">会员ID</param>
        /// <returns></returns>
        public FullShipAddressInfo GetDefaultShipAddress(int uid)
        {
            if (uid < 1)
                throw new Exception("会员ID必须大于0");

            return ShipAddresses.GetDefaultFullShipAddress(uid);
        }

        public bool SetDefaultAddress(int uid, int said,int isDefault=1)
        {
            try
            {
                var result=ShipAddresses.UpdateShipAddressIsDefault(said, uid, isDefault);
                return result;
            }
            catch (Exception e)
            {
                Console.WriteLine(e);
                throw;
            }
        }

        public FullShipAddressInfo GetShipAddress(int uid, int said)
        {
            try
            {
                var addr= ShipAddresses.GetFullShipAddressBySAId(said, uid);
                return  addr;
            }
            catch (Exception e)
            {
                Console.WriteLine(e);
                throw;
            }
        }

        /// <summary>
        /// 删除一条收货地址
        /// </summary>
        /// <param name="Uid">会员ID</param>
        /// <param name="saId">收货ID</param>
        /// <returns></returns>
        public bool DelShipAddress(int Uid, int saId)
        {
            //参考链接：http://localhost:8033/api/user/delShipAddress?uid=1&said=9
            bool result = ShipAddresses.DeleteShipAddress(saId, Uid);
            return result;
        }

        /// <summary>
        /// 添加收货人地址
        /// </summary>
        /// <param name="uid">会员ID</param>
        /// <param name="regionId">省、市、县的地址ID</param>
        /// <param name="address">详细地址</param>
        /// <param name="consignee">收货人姓名</param>
        /// <param name="mobile">手机</param>
        /// <param name="phone">电话</param>
        /// <param name="email">邮箱</param>
        /// <param name="isDefault">是否当做默认收货地址(0 不是, 1 是)</param>
        /// <param name="zipcode">邮编</param>
        /// <param name="alias">地址别名</param>
        /// <returns>添加成功，返回主键ID</returns>
        public int AddShipAddress(int uid, int regionId, string address, string consignee, string mobile, string phone = "", string email = "", int isDefault = 1, string zipcode = "", string alias = "")
        {
            //参考链接：http://localhost:8033/api/user/addShipAddress?uid=1&saId=8&regionid=2142&isdefault=1&address=收货地址&consignee=收货人3&mobile=13688888888

            string msg = CheckAddress(regionId, alias, consignee, mobile, phone, email, zipcode, address);
            if (msg.Length > 0)
                throw new Exception(msg);

  
            ShipAddressInfo shipAddressInfo = new ShipAddressInfo();
            shipAddressInfo.Uid = uid;
            shipAddressInfo.RegionId = regionId;
            shipAddressInfo.IsDefault = isDefault == 0 ? 0 : 1;
            shipAddressInfo.Alias = WebHelper.HtmlEncode(alias);
            shipAddressInfo.Consignee = WebHelper.HtmlEncode(consignee);
            shipAddressInfo.Mobile = mobile;
            shipAddressInfo.Phone = phone;
            shipAddressInfo.Email = email;
            shipAddressInfo.ZipCode = zipcode;
            shipAddressInfo.Address = WebHelper.HtmlEncode(address);
            int saId = ShipAddresses.CreateShipAddress(shipAddressInfo);

            return saId;
        }

        /// <summary>
        /// 修改收货人地址
        /// </summary>
        /// <param name="uid">会员ID</param>
        /// <param name="saId">收货人主键ID</param>
        /// <param name="regionId">省、市、县的地址ID</param>
        /// <param name="address">详细地址</param>
        /// <param name="consignee">收货人姓名</param>
        /// <param name="mobile">手机</param>
        /// <param name="phone">电话</param>
        /// <param name="email">邮箱</param>
        /// <param name="isDefault">是否当做默认收货地址(0 不是, 1 是)</param>
        /// <param name="zipcode">邮编</param>
        /// <param name="alias">地址别名</param>
        /// <returns></returns>
        public bool EditShipAddress(int uid, int saId, int regionId, string address, string consignee, string mobile, string phone = "", string email = "", int isDefault = 1, string zipcode = "", string alias = "")
        {
            //参考链接：http://localhost:8033/api/user/editShipAddress?uid=1&saId=8&regionid=2142&isdefault=1&address=收货地址&consignee=收货人3&mobile=13688888888
            string msg = CheckAddress(regionId, alias, consignee, mobile, phone, email, zipcode, address);

            if (msg.Length > 0)
                throw new Exception(msg);

            ShipAddressInfo shipAddressInfo = ShipAddresses.GetShipAddressBySAId(saId, uid);
            if (shipAddressInfo == null)
                throw new Exception("配送地址不存在");//检查地址

            shipAddressInfo.Uid = uid;
            shipAddressInfo.RegionId = regionId;
            shipAddressInfo.IsDefault = isDefault == 0 ? 0 : 1;
            shipAddressInfo.Alias = WebHelper.HtmlEncode(alias);
            shipAddressInfo.Consignee = WebHelper.HtmlEncode(consignee);
            shipAddressInfo.Mobile = mobile;
            shipAddressInfo.Phone = phone;
            shipAddressInfo.Email = email;
            shipAddressInfo.ZipCode = zipcode;
            shipAddressInfo.Address = WebHelper.HtmlEncode(address);
            ShipAddresses.UpdateShipAddress(shipAddressInfo);
            return true;
        }

        string CheckAddress(int regionId, string alias, string consignee, string mobile, string phone, string email, string zipcode, string address)
        {
            //检查区域
            RegionInfo regionInfo = Regions.GetRegionById(regionId);
            if (regionInfo == null || regionInfo.Layer != 3)
                return "请选择有效的区域";

            //检查地址别名
            if (alias.Length > 25)
                return "最多只能输入25个字";

            //检查收货人
            if (string.IsNullOrWhiteSpace(consignee))
                return "收货人不能为空";
            else if (consignee.Length > 10)
                return "最多只能输入10个字";

            //检查手机号和固话号
            if (string.IsNullOrWhiteSpace(mobile) && string.IsNullOrWhiteSpace(phone))
                return "手机号和固话号必填一项";
            else
            {
                if (!ValidateHelper.IsMobile(mobile))
                    return "手机号格式不正确";
                if (!ValidateHelper.IsPhone(phone))
                    return "固话号格式不正确";
            }

            //检查邮箱
            if (!ValidateHelper.IsEmail(email))
                return "邮箱格式不正确";

            //检查邮编
            if (!ValidateHelper.IsZipCode(zipcode))
                return "邮编格式不正确";

            //检查详细地址
            if (string.IsNullOrWhiteSpace(address))
                return "详细地址不能为空";
            else if (address.Length > 75)
                return "最多只能输入75个字";

            return "";
        }

        #endregion

        #region 商品收藏
        /// <summary>
        /// 添加商品到收藏夹
        /// </summary>
        /// <param name="Uid">会员ID</param>
        /// <param name="pid">产品ID</param>
        /// <returns></returns>
        public bool AddProductFavorite(int Uid, int pid)
        {
            //参考链接：http://localhost:8033/api/user/AddProductToFavorite?uid=1&pid=50
            if (Uid < 1 || pid < 1)
                throw new Exception("会员ID和商品ID必须大于0");

            PartProductInfo partProductInfo = Products.GetPartProductById(pid);
            if (partProductInfo == null)
                throw new Exception("请选择商品");
            //店铺信息
            StoreInfo storeInfo = Stores.GetStoreById(partProductInfo.StoreId);
            if (storeInfo.State != (int)StoreState.Open)
                throw new Exception("店铺不存在");

            //当收藏夹中已经存在此商品时
            if (FavoriteProducts.IsExistFavoriteProduct(Uid, pid))
                throw new Exception("商品已经存在");

            

            bool result = FavoriteProducts.AddProductToFavorite(Uid, pid, 0, DateTime.Now);

            if (result) //添加成功
                return true;
            else //添加失败
                return false;
        }

        /// <summary>
        /// 删除收藏夹中的商品
        /// </summary>
        public bool DelProductFavorite(int Uid, int pid)
        {
            try
            {
                bool result = FavoriteProducts.DeleteFavoriteProductByUidAndPid(Uid, pid);
                if(!result)
                    throw new Exception("取消失败");

                return true;   //删除成功
            }
            catch (Exception e)
            {
                Console.WriteLine(e);
                throw;
            }
            
        }

        public bool ProductFavorite(int uid, int pid)
        {
            try
            {
                var r = FavoriteProducts.IsExistFavoriteProduct(uid, pid);
                if (r)
                {
                    FavoriteProducts.DeleteFavoriteProductByUidAndPid(uid, pid);
                }
                else
                {
                    FavoriteProducts.AddProductToFavorite(uid, pid,0,DateTime.Now);
                }
                return true;
            }
            catch (Exception e)
            {
                Console.WriteLine(e);
                throw;
            }
        }

        /// <summary>
        /// 收藏夹商品列表
        /// </summary>
        /// <param name="uid">会员ID</param>
        /// <param name="page">当前页</param>
        /// <param name="pageSize">每页条数</param>
        /// <returns></returns>
        public ProductFavoriteListModel GetProductFavoriteList(int uid,int page = 1, int pageSize = 10)
        {
            //参考链接：http://localhost:8033/api/user/GetProductFavoriteList?uid=1&page=1&pagesize=10

            PageModel pageModel = new PageModel(pageSize, page, FavoriteProducts.GetFavoriteProductCount(uid));
            ProductFavoriteListModel model = new ProductFavoriteListModel()
            {
                ProductList = CommonHelper.DataTableToList(FavoriteProducts.GetFavoriteProductList(pageModel.PageSize, pageModel.PageNumber, uid)),
                PageModel = pageModel
            };
            return model;
        }

        public bool CheckProductFavorite(int uid, int pid)
        {
            try
            {
                var r=FavoriteProducts.IsExistFavoriteProduct(uid, pid);
                return r;
            }
            catch (Exception e)
            {
                Console.WriteLine(e);
                throw;
            }
        }

        #endregion

        #region 优惠券
        /// <summary>
        /// 获取用户的优惠券
        /// </summary>
        /// <param name="type">类型(0代表全部，1代表未使用，2代表已使用，3代表已过期)</param>
        /// <param name="uid"></param>
        /// <returns></returns>
        public CouponListModel CouponList(int type, int uid)
        {
            try
            {
                CouponListModel model = new CouponListModel()
                {
                    ListType = type,
                    CouponList = Coupons.GetCouponList(uid, type)
                };
                return model;
            }
            catch (Exception e)
            {
                Trace.TraceError(e.StackTrace);
                throw;
            }
        }
        #endregion

        #region  订单评价

        /// <summary>
        /// 评价商品
        /// </summary>
        /// <param name="oid">订单id</param>
        /// <param name="recordId">订单商品记录id</param>
        /// <param name="message">评价内容</param>
        /// /// <param name="star">星星</param>
        public string ReviewProduct(int oid,int recordId,string message,string pic1="",string pic2="",string pic3="",string pic4="",int star=5)
        {
            

            if (star > 5 || star < 1)
                throw new Exception("请选择正确的星星");

            if (message.Length == 0)
                throw new Exception("请填写评价内容");
            if (message.Length > 100)
                throw new Exception("评价内容最多输入100个字");
            //禁止词
            string bannedWord = FilterWords.GetWord(message);
            if (bannedWord != "")
                throw new Exception("评价内容中不能包含违禁词");

            OrderInfo orderInfo = Orders.GetOrderByOid(oid);
            if (orderInfo == null )
                throw new Exception("订单不存在");
            if (orderInfo.OrderState != (int)OrderState.Received)
                throw new Exception("订单还未收货,不能评价");

            OrderProductInfo orderProductInfo = null;
            List<OrderProductInfo> orderProductList = Orders.GetOrderProductList(oid);
            foreach (OrderProductInfo item in orderProductList)
            {
                if (item.RecordId == recordId)
                {
                    orderProductInfo = item;
                    break;
                }
            }
            if (orderProductInfo == null)
                throw new Exception("商品不存在");
            //商品已评价
            if (orderProductInfo.IsReview == 1)
                throw new Exception("商品已经评价");
            var partUserInfo = Users.GetPartUserById(orderInfo.Uid);
            int payCredits = Credits.SendReviewProductCredits(orderInfo.StoreId, ref partUserInfo, orderProductInfo, DateTime.Now);
            ProductReviewInfo productReviewInfo = new ProductReviewInfo()
            {
                Pid = orderProductInfo.Pid,
                Uid = orderProductInfo.Uid,
                OPRId = orderProductInfo.RecordId,
                Oid = orderProductInfo.Oid,
                ParentId = 0,
                State = 0,
                StoreId = orderProductInfo.StoreId,
                Star = star,
                Quality = 0,
                Message = WebHelper.HtmlEncode(FilterWords.HideWords(message)),
                ReviewTime = DateTime.Now,
                PayCredits = payCredits,
                PName = orderProductInfo.Name,
                PShowImg = orderProductInfo.ShowImg,
                BuyTime = orderProductInfo.AddTime,
                IP = WebHelper.GetIP(),
                ReviewPic_1 = pic1,
                ReviewPic_2 = pic2,
                ReviewPic_3 = pic3,
                ReviewPic_4 = pic4
            };
            ProductReviews.ReviewProduct(productReviewInfo);

            orderProductInfo.IsReview = 1;
            if (Orders.IsReviewAllOrderProduct(orderProductList) && Stores.GetStoreReviewByOid(oid) != null)
                Orders.UpdateOrderIsReview(oid, 1);

             return recordId.ToString();
        }
        /// <summary>
        /// 获取用户的商品评价列表
        /// </summary>
        /// <param name="uid">用户编号</param>
        /// <param name="pageSize"></param>
        /// <param name="pageNumber"></param>
        /// <returns></returns>
        public IList<ProductReviewInfo> GetUserProductReviewList(int uid, int pageSize=15, int pageNumber=1)
        {
            return ProductReviews.GetUserProductReviewList(uid, pageSize, pageNumber);
        }

        #endregion

        #region 预约
        /// <summary>
        /// 预约申请
        /// </summary>
        /// <param name="apply"></param>
        /// <returns></returns>
        public int AppointApply(AppointApplyInputDto apply)
        {
            try
            {
                if (ProductAppointManager.Check(apply.Uid, apply.ApplyTime))
                {
                    throw new Exception("预约已经存在");
                }
                if(apply.Uid<=0)
                    throw new Exception("用户参数格式错误");
                var partUserInfo = Users.GetPartUserById(apply.Uid);
                var app = new ProductAppoint();
                if (apply.Pid > 0)
                {
                    var product = Products.GetProductById(apply.Pid);
                    app.Pid = product.Pid;
                    app.PName = product.Name;
                    app.PShowImg = product.ShowImg;
                    app.StoreId = product.StoreId;
                }
                if(app.StoreId==0)
                    app.StoreId = partUserInfo.RegisterFromStoreId;
                app.ApplyTime = apply.ApplyTime;
                app.Remark = apply.Remark;
                app.Status = 0;
                app.Uid = apply.Uid;
                app.RealName = apply.RealName;
                app.Phone = apply.Phone;
                app.AppointType = apply.AppointType;
                app.DiningTableTypeId = apply.DiningTableTypeId;
                app.DiningTableUserTotal = apply.DiningTableUserTotal ?? "";
                app.DiningTableTypeName = apply.DiningTableTypeName ?? "";
                var r=ProductAppointManager.AddAppoint(app);
                Orders.SendStoreAppointAddMessage(app.AppointId);
                return r;
            }
            catch (Exception e)
            {
                Trace.TraceError(e.StackTrace);
                throw;
            }
        }
        /// <summary>
        /// 预约取消
        /// </summary>
        /// <param name="aid">预约ID</param>
        /// <returns></returns>
        public bool AppointCancel(int aid)
        {
            try
            {
                return ProductAppointManager.UpdateAppointStatus(aid,1);
            }
            catch (Exception e)
            {
                Trace.TraceError(e.StackTrace);
                throw;
            }
        }
        /// <summary>
        /// 预约列表
        /// </summary>
        /// <param name="uid"></param>
        /// <returns></returns>
        public List<AppointApplyOutDto> AppointList(int uid)
        {
            try
            {
                var result = new List<AppointApplyOutDto>();
                var dbResult = ProductAppointManager.GetProductAppointList(uid);
                //预约状态0，待确认，1：已取消，2：已确认，3：被拒绝
                foreach (var appoint in dbResult)
                {
                    string s;
                    switch (appoint.Status)
                    {
                        case 1:
                            s = "已取消";
                            break;
                        case 2:
                            s = "已确认";
                            break;
                        case 3:
                            s = "已拒绝";
                            break;
                        default:
                            s = "待确认";
                            break;
                    }
                    var t = new AppointApplyOutDto
                    {
                        Pid = appoint.Pid,
                        PName =appoint.PName,
                        AId = appoint.AppointId,
                        ApplyTime = appoint.ApplyTime,
                        Status = s,
                        Uid = appoint.Uid,
                        Remark = appoint.Remark,
                        PShowImg = appoint.PShowImg,
                        RealName = appoint.RealName,
                        Phone = appoint.Phone,
                        StoreId = appoint.StoreId,
                        AppointType = appoint.AppointType,
                        DiningTableUserTotal = appoint.DiningTableUserTotal,
                        DiningTableTypeId = appoint.DiningTableTypeId,
                        DiningTableTypeName = appoint.DiningTableTypeName
                    };
                    result.Add(t);
                }
                
                
                
                return result;
            }
            catch (Exception e)
            {
                Trace.TraceError(e.StackTrace);
                throw;
            }
        }

        #endregion

        #region 积分
        /// <summary>
        /// 获取积分记录
        /// </summary>
        /// <param name="uid">用户编号</param>
        /// <param name="type">类型(2代表全部类型，0代表收入，1代表支出)</param>
        /// <param name="page">当前页</param>
        /// <returns></returns>
        public PayCreditLogListModel PayCreditLog(int uid,int type=2,int page=1)
        {
            try
            {
                var pageModel = new PageModel(15, page, Credits.GetPayCreditLogCount(uid, type));
                var model = new PayCreditLogListModel()
                {
                    ListType = type,
                    PageModel = pageModel,
                    PayCreditLogList = Credits.GetPayCreditLogList(uid, type, pageModel.PageSize, pageModel.PageNumber)
                };
                return model;
            }
            catch (Exception e)
            {
                Trace.TraceError(e.Message);
                throw;
            }

            
        }

        #endregion
    }
}